package com.zwy.core.utils;

import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Base64;

/**
 * 密钥生成工具类，用于通过指定字符串生成符合 HS512 算法要求的密钥
 */
public class JwtKeyGenerator {

    /**
     * 使用 SHA-512 哈希算法生成 512 位密钥
     * @param input 指定的输入字符串
     * @return Base64 编码的密钥
     */
    public static String generateKeyFromHash(String input) {
        try {
            MessageDigest digest = MessageDigest.getInstance("SHA-512");
            byte[] hash = digest.digest(input.getBytes(StandardCharsets.UTF_8));
            return Base64.getEncoder().encodeToString(hash);
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("SHA-512 algorithm not found", e);
        }
    }

    /**
     * 使用指定字符串作为种子生成随机密钥
     * @param seed 指定的种子字符串
     * @return Base64 编码的密钥
     */
    public static String generateKeyFromSeed(String seed) {
        try {
            SecureRandom secureRandom = SecureRandom.getInstanceStrong();
            secureRandom.setSeed(seed.getBytes(StandardCharsets.UTF_8));
            
            KeyGenerator keyGenerator = KeyGenerator.getInstance("HmacSHA512");
            keyGenerator.init(512, secureRandom);
            SecretKey secretKey = keyGenerator.generateKey();
            
            return Base64.getEncoder().encodeToString(secretKey.getEncoded());
        } catch (Exception e) {
            throw new RuntimeException("Error generating key from seed", e);
        }
    }

    /**
     * 生成随机密钥（不依赖指定字符串）
     * @return Base64 编码的密钥
     */
    public static String generateRandomKey() {
        try {
            SecureRandom secureRandom = SecureRandom.getInstanceStrong();
            byte[] keyBytes = new byte[64]; // 512 bits = 64 bytes
            secureRandom.nextBytes(keyBytes);
            return Base64.getEncoder().encodeToString(keyBytes);
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("SecureRandom algorithm not found", e);
        }
    }

    public static void main(String[] args) {
        String input = "zhougeishandsome"; // 指定的输入字符串
        
        System.out.println("使用 SHA-512 哈希生成的密钥:");
        System.out.println(generateKeyFromHash(input));
        
        System.out.println("\n使用指定字符串作为种子生成的密钥:");
        System.out.println(generateKeyFromSeed(input));
        
        System.out.println("\n随机生成的密钥:");
        System.out.println(generateRandomKey());
    }
}